package leetcode;

import java.util.ArrayList;
import java.util.List;

public class code257 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(1);
        treeNode.left = new TreeNode(2);
        treeNode.right = new TreeNode(3);
        treeNode.left.right = new TreeNode(5);
        treeNode.right.right = new TreeNode(9);
        treeNode.right.left = new TreeNode(7);
        treeNode.left.left = new TreeNode(4);
        treeNode.left.left.right = new TreeNode(6);
        treeNode.right.right.right = new TreeNode(10);
        treeNode.right.right.left = new TreeNode(8);
        treeNode.right.right.right.right = new TreeNode(11);
        treeNode.right.right.right.right.right = new TreeNode(12);
        treeNode.right.right.right.right.right.right = new TreeNode(13);
        treeNode.right.right.right.right.right.right.right = new TreeNode(14);

        System.out.println(binaryTreePaths(treeNode));
    }

    static List<String> list = new ArrayList<>();
    static int index = 0;
    static StringBuffer res = new StringBuffer();

    public static List<String> binaryTreePaths(TreeNode root) {
        backtrack(root, new ArrayList<>());
        return list;
    }

    private static void backtrack(TreeNode root, List<TreeNode> stringBuffer) {
        if (root.left == null && root.right == null) {
            stringBuffer.add(root);
            index++;

            for (int i = 0; i < stringBuffer.size(); i++) {
                if (i>=1)
                    res.append("->");
                res.append(stringBuffer.get(i).val);
            }
            list.add(res.toString());
            res.delete(0,res.length());
        } else {
            stringBuffer.add(root);
            index++;
            if (root.left != null) {
                backtrack(root.left, stringBuffer);
                stringBuffer.remove(index-1);
                index--;
            }
            if (root.right != null) {
                backtrack(root.right, stringBuffer);
                stringBuffer.remove(index-1);
                index--;
            }

        }
    }
}
